import 'package:flutter/material.dart';
import 'package:flutter_trip/dao/search_dao.dart';
import 'package:flutter_trip/widget/search_textfiled.dart';

import '../model/seach_model.dart';
import '../widget/fwebview.dart';
const SEARCH_URL =
    'https://m.ctrip.com/restapi/h5api/globalsearch/search?source=mobileweb&action=mobileweb&keyword=';
const TYPES = [
  'channelgroup',
  'gs',
  'plane',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];

class SearchPage extends StatefulWidget {
  final bool? showBackButton;
  final String? searchUrl;
  final String? keyWord;

  const SearchPage({super.key, this.showBackButton = false, this.searchUrl = SEARCH_URL, this.keyWord});
  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String? keyWord;
  List<SearchItem>? searchList = [];

  @override
  void initState() {
    if (widget.keyWord != null) {
      _onChangeText(widget.keyWord!);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            Container(
              height: 88,
              child: Column(
                children: [
                  Container(
                    height: 44,
                  ),
                  SearchBar(showBackButton: widget.showBackButton,
                    onChangeText: _onChangeText,keyWord: widget.keyWord,),
                ],
              ),
            ),
            MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: Expanded(
                    flex: 1,
                    child: ListView.builder(
                        itemCount: searchList!.length,
                        itemBuilder: (BuildContext context, int index) {
                          return _item(index);
                        })
                )
            ),
          ],
        ),
      ),
    );
  }

  _onChangeText(String text) {
    keyWord = text;
    if (text.length == 0) {
      setState(() {
        searchList = [];
      });
      return;
    }
    String urlStr = widget.searchUrl! + text;
    SearchDao.fetch(urlStr, text).then((value) {
      if (value.keyword == keyWord && value.data != null) {
        setState(() {
          searchList = value.data;
          print('');
        });
      }
    }).catchError((e) {

    });
  }

  _item(int index) {
    SearchItem searchItem = searchList![index];
    if (searchItem == null) {
      return null;
    }
    return GestureDetector(
      onTap: () {
        Navigator.push(context,MaterialPageRoute(builder: (context) => FWebView(url: searchItem.url,title: '详情',)));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(width: 0.5, color: Colors.grey),
            )
        ),
        child: Row(
          children: [
            Image(
              image: AssetImage(_typeImagPath(searchItem.type)),
              width: 26,
              height: 26,
            ),
            Expanded(
              flex: 1,
              child: Column(
                  crossAxisAlignment:CrossAxisAlignment.start,
                children: [
                  Container(
                    child: _title(searchItem),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 2, top: 5),
                    child: _subTitle(searchItem),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _typeImagPath(String? type) {
    if (type == null) return 'images/type_travelgroup.png';
    String path = 'travelgroup';
    for (final value in TYPES) {
      if (type.contains(value)) {
        path = value;
        break;
      }
    }
    return 'images/type_$path.png';
  }

  _subTitle(SearchItem? searchItem) {
    if (searchItem == null) return null;
    List<TextSpan> list = [];
    TextSpan textSpan1 = TextSpan(
      text: searchItem.price ?? "",
      style: TextStyle(fontSize: 16, color: Colors.orange),
    );
    TextSpan textSpan2 = TextSpan(
      text: '' + (searchItem.star ?? ""),
      style: TextStyle(fontSize: 12, color: Colors.grey),
    );
    list.add(textSpan1);
    list.add(textSpan2);
    return RichText(text: TextSpan(children: list));
  }

  _title(SearchItem? searchItem) {
    if (searchItem == null) return null;
    List<TextSpan> list = [];
    TextSpan textSpan1 = TextSpan(
      text: '' + (searchItem.districtname ?? "") + '' +
          (searchItem.zonename ?? ""),
      style: TextStyle(fontSize: 16, color: Colors.grey),
    );
    list.addAll(_keyWordSpans(searchItem.word,keyWord!));
    list.add(textSpan1);
    return RichText(text: TextSpan(children: list));
  }

  _keyWordSpans(String? word, String keyword) {
    List<TextSpan> spans = [];
    if (word == null || word.length == 0) return spans;
    String wordL = word.toLowerCase(),
        keywordL = keyword.toLowerCase();
    List<String> arr = wordL.split(keywordL);
    TextStyle normalStyle = TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle = TextStyle(fontSize: 16, color: Colors.orange);
    //'wordwoc'.split('w') -> [, ord, oc] @https://www.tutorialspoint.com/tpcg.php?p=wcpcUA

    int preIndex = 0;
    for (int i = 0; i < arr.length; i++) {
      if (i != 0) {
        //搜索关键字高亮忽略大小写
        preIndex = wordL.indexOf(keywordL, preIndex);
        spans.add(TextSpan(
            text: word.substring(preIndex, preIndex + keyword.length),
            style: keywordStyle));
      }
      String val = arr[i];
      if (val != null && val.length > 0) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }
    }
    return spans;
   }
  }
  



class SearchBar extends StatefulWidget {
  final bool? showBackButton;
  final ValueChanged<String>? onChangeText;
  final String? keyWord;
  const SearchBar({super.key, this.showBackButton, this.onChangeText, this.keyWord});

  @override
  State<SearchBar> createState() => _SearchBarState();
}

class _SearchBarState extends State<SearchBar> {
  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Row(
        children: [
          if(widget.showBackButton! ?? false) Container(
            padding: EdgeInsets.only(left: 10),
            child: GestureDetector(
              onTap: (){
                _backTap(context);
              },
              child: Icon(
                Icons.arrow_back_ios,
                size: 20,
              ),
            )

          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 10),
               child: SearchTextFiled(defaultText: widget.keyWord ?? "",onChangeText: widget.onChangeText,),
            ),
          ),
          Container(
            padding: EdgeInsets.only(right: 10,left: 10),
            child: Text(
              '搜索',
              style: TextStyle(
                fontSize: 14,
                color: Colors.blue,
              ),
            ),
          )
        ],
      ),
    );
  }

  _backTap(BuildContext context){
   Navigator.pop(context);
  }
}
